#!/bin/bash
###############################################################
#For Better or worse these options will mirror record.sh
DIR=/mnt/tv
#use the ids its probably better
hdhomerun_ip1=13127056
hdhomerun_ip2=13202689
comskip_dir=/root/comskip81_036_donators
projectx_dir=/root/projectx/Project-X_0.91.0
mangler=/root/newsmangler/mangler.py
mangler_config=/root/newsmangler/docs/sample.conf
rar=/opt/bin/rar
XPORT=/root/xport.exe

SCPHOST=CHANGEME
SCPBASE=CHANGEME #You have to escape the spaces yourself
SCPUSERNAME=CHANGEME

FTPUSERNAME=CHANGEME
FTPPASSWORD=CHANGEME
FTPHOST=CHANGEME
FTPDIR=CHANGEME
#NZBDIR is probably the home directory of the user running this cronjob my case /root
NZBDIR=/root
####################################################################


#Some Files we need
ffmpeg=`which ffmpeg`
hdhomerun_config=`which hdhomerun_config`
wine=`which wine`
java=`which java`
mysql=`which mysql`
ssh=`which ssh`
scp=`which scp`
par=`which par2create`
xml=`which xml`
mediainfo=`which mediainfo`
mkvmerge=`which mkvmerge`
scp=`which scp`
ncftpput=`which ncftpput`
curl=`which curl`


file=$1
FILENAME=`basename $file`
FILENAME_NOEXT=${FILENAME%.*}
echo $FILENAME $FILENAME_NOEXT
#this makes it go to / if running in crontab so we need to lock it
while [ -e /tmp/xport.lock ]; do
	echo "Waiting for export"
	sleep 1
done
trap ctrl_c INT

function ctrl_c() {
        echo "** Trapped CTRL-C"
        rm /tmp/xport.lock
        echo "See Ya!"
        exit
}

touch /tmp/xport.lock

wine $XPORT $1 1 1 1

#mv the files where they belong (and rename them)
if [ -e "bits0001.mpv" ]; then
	echo "Great found the bits file here!"
	mv bits0001.mpv $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpv
	mv bits0001.mpa $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpa	
else
	echo "Defaulting the bits files back to / Maybe run from cron? It's ok though"
	mv /bits0001.mpv $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpv
	mv /bits0001.mpa $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpa
fi




#The ProjectX Audio seems to work, but for some reason not the xport.... Maybe only when compiling gcc???
rm /tmp/xport.lock
mv $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpg $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpg.orig
remux it
ffmpeg -i $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpv -i $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpa -vcodec copy -acodec copy -f vob $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpg


echo "Running Comskip"
$wine $comskip_dir/comskip.exe -t --ini $comskip_dir/comskip.ini $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpg > $DIR/$FILENAME_NOEXT/comskip_fix_gop.log 2>&1
COM=$?
echo "Comskip Completed with $COM"
if [ $COM -gt 1 ]; then
        echo "Comskip Failed"
        exit
fi
echo "Starting ProjectX"
$java -jar $projectx_dir/ProjectX.jar -out $DIR/$FILENAME_NOEXT -cut $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpg.Xcl $DIR/$FILENAME_NOEXT/$FILENAME_NOEXT.mpg > $DIR/$FILENAME_NOEXT/projectx_fix_gop.log 2>&1
COM=$?
echo "ProjectX Completed with $?"
if [ $COM != 0 ]; then
        echo "ProjectX Failed"
        exit
fi
